<template>
  <div class="container">
    <h1>水果识别系统</h1>
    
    <div class="upload-area">
      <label for="file-upload" class="upload-label">
        点击上传水果图片
        <input 
          id="file-upload" 
          type="file" 
          accept="image/*" 
          @change="handleFileUpload"
          class="file-input"
        >
      </label>
      
      <div v-if="selectedImage" class="image-preview">
        <img :src="selectedImage" alt="预览图片" class="preview-img">
        <button @click="detectFruits" class="detect-btn">识别水果</button>
      </div>
    </div>
    
    <!-- 优化部分：直接显示水果名称和可信度 -->
    <div v-if="results.length > 0" class="results">
      <h2>识别结果：</h2>
      <ul>
        <!-- 循环每个识别结果，直接显示水果名称 -->
        <li v-for="(result, index) in results" :key="index">
          <!-- 显示首字母大写的水果名称 + 可信度 -->
          {{ capitalize(result.fruit) }} - 可信度: {{ result.confidence }}%
        </li>
      </ul>
    </div>
    
    <div v-if="message" class="message">{{ message }}</div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import axios from 'axios';

// 存储选择的图片
const selectedImage = ref(null);
// 存储识别结果
const results = ref([]);
// 存储提示信息
const message = ref('');

// 处理文件上传
const handleFileUpload = (event) => {
  const file = event.target.files[0];
  if (file) {
    selectedImage.value = URL.createObjectURL(file);
    results.value = [];
    message.value = '';
  }
};

// 发送图片到后端进行识别
const detectFruits = async () => {
  if (!selectedImage.value) return;
  
  message.value = '正在识别中，请稍候...';
  
  try {
    const formData = new FormData();
    const fileInput = document.getElementById('file-upload');
    formData.append('file', fileInput.files[0]);
    
    const response = await axios.post('http://localhost:8000/predict', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    
    results.value = response.data.predictions;
    
    if (results.value.length === 0) {
      message.value = '没有识别到任何水果，请尝试另一张图片。';
    } else {
      message.value = '';
    }
  } catch (error) {
    message.value = '识别失败，请检查后端是否已启动。';
    console.error(error);
  }
};

// 新增：将水果名称首字母大写（比如 apple → Apple）
const capitalize = (str) => {
  if (!str) return '';
  return str.charAt(0).toUpperCase() + str.slice(1);
};

// 新增：如果需要显示中文名称（比如 apple → 苹果），可以添加这个映射表
// const fruitChineseNames = {
//   'apple': '苹果',
//   'banana': '香蕉',
//   'orange': '橙子',
//   'grape': '葡萄',
//   'watermelon': '西瓜',
//   'strawberry': '草莓',
//   'pineapple': '菠萝'
// };
// 然后在模板中使用：{{ fruitChineseNames[result.fruit] }}
</script>

<style>
/* 样式保持不变 */
.container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  text-align: center;
  font-family: Arial, sans-serif;
}

h1 {
  color: #333;
}

.upload-area {
  margin: 30px 0;
}

.upload-label {
  display: inline-block;
  padding: 15px 30px;
  background-color: #42b983;
  color: white;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.upload-label:hover {
  background-color: #359e75;
}

.file-input {
  display: none;
}

.image-preview {
  margin-top: 20px;
}

.preview-img {
  max-width: 100%;
  max-height: 400px;
  border-radius: 5px;
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

.detect-btn {
  margin-top: 15px;
  padding: 10px 20px;
  background-color: #2196f3;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.detect-btn:hover {
  background-color: #0b7dda;
}

.results {
  margin-top: 30px;
  text-align: left;
  background-color: #f5f5f5;
  padding: 20px;
  border-radius: 5px;
}

.results ul {
  list-style-type: none;
  padding: 0;
}

.results li {
  padding: 8px 0;
  border-bottom: 1px solid #eee;
}

.message {
  margin-top: 20px;
  padding: 10px;
  border-radius: 5px;
  color: #666;
}
</style>
